<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件,通用公共函数
function returnJson($code = '', $msg = '', $data = '', $extra = '', $add_extra='',$add_add_extra='', $add_add_add_extra='')
{
    $msgArray = [];
    $msgArray['code'] = $code?$code:200;
    !empty($msg)&&($msgArray['msg'] = $msg);
    ($data !== '')&&($msgArray['data'] = $data);
    ($extra !== '')&&($msgArray['extra'] = $extra);
    ($add_extra !== '')&&($msgArray['add_extra'] = $add_extra);
    ($add_add_extra !== '')&&($msgArray['add_add_extra'] = $add_add_extra);
    ($add_add_add_extra !== '')&&($msgArray['add_add_add_extra'] = $add_add_add_extra);
    return json($msgArray);
}
//获取用户id的方法
function get_user_id($token){
    return strstr( $token,"_",true );
}

function curl($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, FALSE);  //不返回报文头部
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); //// https请求 不验证证书和hosts
    $data = curl_exec($curl);
    curl_close($curl);
    return $data;
}

//获取用户登陆真实ip
function get_real_ip(){
	if(!empty($_SERVER['HTTP_CLIENT_IP'])){
		$cip = $_SERVER['HTTP_CLIENT_IP'];
    }else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
    {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }else if(!empty($_SERVER["REMOTE_ADDR"]))
    {
        $cip = $_SERVER["REMOTE_ADDR"];
    }else
    {
        $cip = '';
    }
    preg_match("/[\d\.]{7,15}/", $cip, $cips);
    $cip = isset($cips[0]) ? $cips[0] : 'unknown';
    unset($cips);
    return $cip;
}

/**
 * 字符串去掉最后几位
 * @param  [type] $str  字符串
 * @param  [type] $num  末尾需要去掉的位数
 * @return [type]       string
 */
function unset_last_string( $str,$num ){
    return substr( $str,0,strlen( $str )-$num );
}

/**
 * 获得每页的条数
 * @return int
 */
function get_list_rows() {
    return 10;
}

/**
 * 获得平台账户基础权限
 * @return string
 */
function get_platform_basic_permission() {
    return "房源管理|租客管理|财务管理|公寓管理权限分配";
}

//处理数组数据
function array_list_count($data){
    $date=json_encode($data,JSON_UNESCAPED_SLASHES);
    $goods_thumbFirst=explode(',',$date);
    $str_replace=str_replace('"','',$goods_thumbFirst);
    $str_replace=str_replace('[','',$str_replace);
    $count=str_replace(']','',$str_replace);
    return $count;
}

/**
 * 发送HTTP请求方法
 * @param  string $url    请求URL
 * @param  array  $params 请求参数
 * @param  string $method 请求方法GET/POST
 * @return array  $data   响应数据
 */
function httpCurl($url, $params, $method = 'POST', $header = array(), $multi = false){
    date_default_timezone_set('PRC');
    $opts = array(
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => $header,
        CURLOPT_COOKIESESSION  => true,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_COOKIE         =>session_name().'='.session_id(),
    );
    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)){
        case 'GET':
            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new Exception('不支持的请求方式！');
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if($error) throw new Exception('请求发生错误：' . $error);
    return  $data;
}


/**
 * 微信信息解密
 * @param  string  $appid  小程序id
 * @param  string  $sessionKey 小程序密钥
 * @param  string  $encryptedData 在小程序中获取的encryptedData
 * @param  string  $iv 在小程序中获取的iv
 * @return array 解密后的数组
 */
function decryptData( $appid , $sessionKey, $encryptedData, $iv ){
    $OK = 0;
    $IllegalAesKey = -41001;
    $IllegalIv = -41002;
    $IllegalBuffer = -41003;
    $DecodeBase64Error = -41004;

    if (strlen($sessionKey) != 24) {
        return $IllegalAesKey;
    }
    $aesKey=base64_decode($sessionKey);

    if (strlen($iv) != 24) {
        return $IllegalIv;
    }
    $aesIV=base64_decode($iv);

    $aesCipher=base64_decode($encryptedData);

    $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
    $dataObj=json_decode( $result );
    if( $dataObj  == NULL )
    {
        return $IllegalBuffer;
    }
    if( $dataObj->watermark->appid != $appid )
    {
        return $DecodeBase64Error;
    }
    $data = json_decode($result,true);

    return $data;
}


/**
 * 请求过程中因为编码原因+号变成了空格
 * 需要用下面的方法转换回来
 */
function define_str_replace($data)
{
    return str_replace(' ','+',$data);
}

function tenant_sex($data){
    $data=$data=='男'? 1 : 2;
    return $data;
}

function tenant_u_sex($data){
    $data=$data==1? '男' : '女';
    return $data;
}

/**
 * best64编码转图片保存
 * @param $base64_image_content 图片best64编码
 * @return bool|string
 */
function base64_image_content($base64_image_content){
    //匹配出图片的格式
    $path='uploads';
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){

        $type = $result[2];
        $new_file = $path."/".date('Ymd',time())."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($new_file, 0700);
        }
        $num=rand(10,100);
        $new_file = $new_file.time().$num.".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return '/'.$new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/**
 * 数字转换为中文
 * @param  integer  $num  目标数字
 */
function number2chinese($num)
{
    if (is_int($num) && $num < 100) {
        $char = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
        $unit = ['', '十', '百', '千', '万'];
        $return = '';
        if ($num < 10) {
            $return = $char[$num];
        } elseif ($num%10 == 0) {
            $firstNum = substr($num, 0, 1);
            if ($num != 10) $return .= $char[$firstNum];
            $return .= $unit[strlen($num) - 1];
        } elseif ($num < 20) {
            $return = $unit[substr($num, 0, -1)]. $char[substr($num, -1)];
        } else {
            $numData = str_split($num);
            $numLength = count($numData) - 1;
            foreach ($numData as $k => $v) {
                if ($k == $numLength) continue;
                $return .= $char[$v];
                if ($v != 0) $return .= $unit[$numLength - $k];
            }
            $return .= $char[substr($num, -1)];
        }
        return $return;
    }
}

/**
 * 两个时间戳之间的月数
 * @param $start
 * @param bool $end
 * @return float|int|string
 * @throws Exception
 */
function get_month_diff($start, $end = FALSE)
{
    $end OR $end = time();
    $start = new DateTime("@$start");
    $end   = new DateTime("@$end");
    $diff  = $start->diff($end);
    return $diff->format('%y') * 12 + $diff->format('%m');
}

/**
 * 两个时间戳之间的天数
 * @param $start
 * @param bool $end
 * @return float|int|string
 * @throws Exception
 */
function get_day_diff($start, $end = FALSE)
{
    $end OR $end = time();
    $start = new DateTime("@$start");
    $end   = new DateTime("@$end");
    $diff  = $start->diff($end);
    return $diff->format('%d');
}

/**
 * 判断指定时间戳是否在指定月内
 * @param $month
 * @param $time
 * @return bool
 */
function get_month_time($month, $time) {
    $start = strtotime($month);
    $end = strtotime($month . ' +1 month -1 day');
    if ($time >= $start && $time <= $end) {
        return true;
    } else {
        return false;
    }
}

function getJson($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}

/**
 * 对价格进行向上或向下取整
 * @param $price    价格
 * @param $decimal  保留小数位数
 * @param $type 1：向上 2：向下
 */
function upDecimal($num, $qty = 2, $type = 1){
    $num2 =  explode('.', $num);
    $dcmnum = $num2[1] ?? 0;
    $subnum = 0;
    if($dcmnum > 0){
        $subnum = bcsub(strlen($dcmnum), $qty, 10);
    }
    $powint = bcpow(10, $qty);
    $num = bcmul($num, $powint, $subnum);
    $numArr = explode('.', $num);
    $num = $numArr[0];
    $dcm = $numArr[1] ?? 0;
    if($dcm > 0){
        if($type == 1 && $num > 0){
            $num = $num + 1;
        }elseif($type == 2 && $num < 0){
            $num = $num - 1;
        }
    }
    return bcdiv($num, $powint, $qty);
}
//获取平台id的方法
function create_id($token){
    $id=strstr( $token,"_",true );
    $model=new \app\manage\model\UserRole();
    $create_id=$model->create_id($id);
    return $create_id;
}
/**
 * get_page_url 获取完整URL
 * @return url
 */
function get_page_url($type = 0){
    $pageURL = 'http';
    if($_SERVER["HTTPS"] == 'on'){
        $pageURL .= 's';
    }
    $pageURL .= '://';
    if($type == 0){
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }else{
        $pageURL .= $_SERVER["SERVER_NAME"];
    }
    return $pageURL;
}
/**
 * @desc arraySort php二维数组排序 按照指定的key 对数组进行自然排序
 * @param array $arr 将要排序的数组
 * @param string $keys 指定排序的key
 * @param string $type 排序类型 asc | desc
 * @return array
 */
function arraySort($arr, $keys, $type = 'asc')
{
    $keysvalue = $new_array = array();
    foreach ($arr as $k => $v) {
        $keysvalue[$k] = $v[$keys];
    }

    if ($type == 'asc') {
        natsort($keysvalue);
    }
    if ($type == 'desc') {
        natsort($keysvalue);
        $keysvalue = array_reverse($keysvalue, TRUE); // 将原数组中的元素顺序翻转,如果第二个参数指定为 true，则元素的键名保持不变
    }
    foreach ($keysvalue as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;

}
//get请求
function curl_get_https($url){
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
    $tmpInfo = curl_exec($curl);     //返回api的json对象
    //关闭URL请求
    curl_close($curl);
    return $tmpInfo;    //返回json对象

}

/**
 * 获取当前系统时间(精确到微秒)
 * @return float
 */
function getMicrosecond() {
    list($t1, $t2) = explode(' ', microtime());
    return sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000000);
}

/**
 * 获取指定月份的第一天开始和最后一天结束的时间戳
 *
 * @param int $y 年份 $m 月份
 * @return array(本月开始时间，本月结束时间)
 */
function mFristAndLast($y="",$m=""){
    if($y=="") $y=date("Y");
    if($m=="") $m=date("m");
    $m=sprintf("%02d",intval($m));
    $y=str_pad(intval($y),4,"0",STR_PAD_RIGHT);

    $m>12||$m<1?$m=1:$m=$m;
    $firstday=strtotime($y.$m."01000000");
    $firstdaystr=date("Y-m-01",$firstday);
    $lastday = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));
    return array("firstday"=>$firstday,"lastday"=>$lastday);
}